package jdbc;

import dao.TeacherDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 利用druid连接池和dbutils工具类操作数据库
 */
public class Test1 {

    private static QueryRunner qr = new QueryRunner();

    public static void main(String[] args) {
        Connection connection = JDBCUtil.getConnection();

        //如果数据库列名与Dao实体不一致可以起别名解决
        String sqlQuery="select * from teacher where  id=?";
        try {
            /**
             * new BeanListHandler<TeacherDao>(TeacherDao.class)
             * TeacherDao.class的作用是,dbutils框架能利用反射创建TeacherDao对象
             * <TeacherDao>的作用是利用泛型指定返回值的类型为List<TeacherDao>
             *
             * 传参时顺序与个数跟sql中的?一一对应
             */
            List<TeacherDao> list = qr.query(connection, sqlQuery, new BeanListHandler<TeacherDao>(TeacherDao.class), "4");
            for (TeacherDao teacherDao : list) {
                System.out.print("id:"+teacherDao.getId()+"\t");
                System.out.print("name:"+teacherDao.getName()+"\t");
                System.out.print(teacherDao.getHobby());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        JDBCUtil.closeConnection(connection,null,null);
    }

}
